<template>
    <v-card-actions class="grid-list-xl justify-center">
        <v-btn
                color="#A34AB0"
                class="ma-2 white--text"
                @click="loginThird('git')"
        >
            GitHubf
            <v-icon right dark>mdi-github-circle</v-icon>
        </v-btn>
        <v-btn
                color="#3B5999"
                class="ma-2 white--text"
                disabled
                @click="loginThird(facebook)"
        >
            FACE BOOK
            <v-icon right dark>mdi-facebook-box</v-icon>
        </v-btn>
        <v-btn
                color="#1DA1F3"
                class="ma-2 white--text"
                disabled
                @click="loginThird(twitter)"
        >
            Twitter
            <v-icon right dark>mdi-twitter-box</v-icon>
        </v-btn>
    </v-card-actions>
</template>

<script>
    export default {
        name: "github",
        data() {
            return {
                client_id: 'Iv1.8af81f83efca6a33',
                client_secret: '126c764b881cd01e1da1bd5b1af56979e540a071',
                scope: 'read:user', // Grants access to read a user's profile data.
                state: '',
                getCodeURL: 'https://github.com/login/oauth/authorize',
                getAccessTokenURL: '/github/login/oauth/access_token',
                getUserURl: 'https://api.github.com/user',
                redirectURL: null,
                code: null,
                accessToken: null,
                signState: false,
                githubImg: "http://111.231.239.202:8018/data/img/project/github.png",
                exitImg: "http://111.231.239.202:8018/data/img/project/exit.png"
            }
        },
        created() {
            //尝试获取地址栏中的code
            this.getUserFromGit();
        },
        methods: {
            /**
             * 从Github获取用户信息
             */
            getUserFromGit() {
                this.getGitCode();
                if (this.code) {
                    //存在code
                    this.accessToken = this.$cookie.get('accessToken');
                    if (this.accessToken) {
                        //获取用户
                        this.getUser()
                    } else {
                        // url中存在code 但是cookie中没有 令牌 => 根据code向 github取 令牌
                        this.getAccessToken();
                    }
                }
            },
            /**
             * 第三方登录
             * @param type
             */
            loginThird(type) {
                //动作分发
                switch (type) {
                    case "git":
                        //支持Git登录
                        this.loginWithGitHub();
                        break;
                    case "facebook":
                        this.$iziToast.warning({message: "博主时间有限，此功能仍在开发中..."});
                        break;
                    case "twitter":
                        this.$iziToast.warning({message: "博主时间有限，此功能仍在开发中..."});
                        break;
                    default:
                        this.$iziToast.warning({message: "你选的几把，连我都不知道?"});
                        break;
                }
            },
            loginWithGitHub() {
                //设置重定向URL
                this.$cookie.set('redirectURL', location.href, 1);
                //域名重定向 获取code
                location.href = this.getCodeURL;
            },
            logout() {
                this.$cookie.delete('accessToken');
                this.signState = false;
                //触发用户登出事件
                this.$emit('logoutEvent')
            },
            getGitCode() {
                this.getCodeURL += ('?' + this.$qs.stringify({
                    client_id: this.client_id,
                    scope: this.scope,
                    state: this.state
                }));
                let parse = this.$qs.parse(location.search.replace("?", ""));
                if (parse.state === this.state) {
                    this.code = parse.code
                }
            },
            getAccessToken() {
                this.$axios.post(this.getAccessTokenURL, {
                    client_id: this.client_id,
                    client_secret: this.client_secret,
                    code: this.code,
                    state: this.state
                }).then((response) => {
                    let result = this.$qs.parse(response.data);
                    //转换github回传的accessToken
                    if (result.error) {
                        console.log(result.error);
                        return;
                    }
                    this.accessToken = result.access_token;
                    if (this.accessToken) {
                        // save to cookie 30 days
                        this.$cookie.set('accessToken', this.accessToken, 30);
                        /*this.redirectURL = this.$cookie.get('redirectURL');
                        if (this.redirectURL) {
                            location.href = this.redirectURL
                        }*/
                        //根据accessToken获取用户
                        this.getUser();


                    }
                })
            },
            getUser() {
                this.$axios.get(this.getUserURl + '?access_token=' + this.accessToken)
                    .then((response) => {
                        let data = response.data;
                        this.signState = true;
                        this.$router.push('/dashboard');
                        // call parent login event
                        this.$emit('loginEvent', {
                            thirdId: data.id,
                            login: data.login,
                            name: data.name,
                            bio: data.bio,
                            avatar: data.avatar_url
                        });
                    })
                    // invaild accessToken
                    .catch((error) => {
                        console.log(error);
                        this.$cookie.delete('accessToken')
                    })
            },
            login: function (user) {
                this.user = user;
                if (user !== undefined) {
                    //入库gitHub提供的用户名和密码
                    this.$axios.post("/api/oauth/store", this.$qs.stringify(user)).then(res => {
                        let result = res.data;
                        if (result) {
                            if (result.code === 200) {
                                this.$store.commit("registerUserData", result.data);
                                //持久化 accessToken、refreshToken 到cookie中
                                let access_token = result.data.access_token;
                                let refresh_token = result.data.refresh_token;
                                this.$cookie.set('echo_access_token', access_token, 30);
                                this.$cookie.set('echo_refresh_token', refresh_token, 30);
                            }
                        }

                    });

                }
            },
        },
        computed: {
            formatCodeURL() {
                return this.getCodeURL + ('?' + this.$qs.stringify({
                    client_id: this.client_id,
                    scope: this.scope,
                    state: this.state
                }))
            }
        }

    }
</script>

<style scoped>
    .oauth-login {
        cursor: pointer;
        height: 25px;
        width: 25px;
    }
</style>